import React, { useState } from 'react';
import {
    Table,
    Button,
    Space,
    message,
    Popconfirm,
    Tag,
    Typography,
    Tree,
    type TreeProps,
    Input,
    Tooltip,
    notification,
    List
} from 'antd';
import {
    PlusOutlined,
    EditOutlined,
    DeleteOutlined,
    EyeOutlined,
    DownloadOutlined,
} from '@ant-design/icons';
import { ApiInfoModal } from './component/ApiInfoModal';
import { LookApiModal } from "./component/LookApiModal";
import { getObject, deleteObject, toast, apis, requestBody, downloadBlob } from "@/service/common";
import type { ApiInfo, ApiMapper, Page } from './txs/types';
import GroupModel from './component/GroupModel';

const { Text } = Typography;


const showImportError = (msgs: string[]) => {
    return <>
        {
            <div
                style={{
                    minHeight: 100,
                    maxHeight: 300,
                    overflowY: 'auto',
                }}
            >
                <List
                    size="small"
                    dataSource={msgs || []}
                    renderItem={(msg, idx) => (
                        <List.Item key={idx} style={{ paddingLeft: 16 }}>
                            <Typography.Text>{msg}</Typography.Text>
                        </List.Item>
                    )}
                    locale={{ emptyText: '无说明' }}
                    bordered
                />
            </div>

        }
    </>
}



const ApiInfoTable: React.FC = () => {
    const [api, contextHolder] = notification.useNotification();

    const [data, setData] = useState<ApiInfo[]>([]);
    const [apiModalVisible, setApiModalVisible] = useState(false);
    const [groupModalVisible, setGroupModalVisible] = useState(false);
    const [lookModalVisible, setLookModalVisible] = useState(false);
    const [currentApi, setCurrentApi] = useState<ApiInfo | null>(null);
    const [loading, setLoading] = useState(false);
    const [page, setPage] = useState<Page>({
        pageNum: 1,
        pageSize: 10,
        total: 10,
        groupIds: null
    });
    const [apiGroupOptions, setApiGroupOptions] = useState<{ title: string; key: number }[]>([{
        title: '无分组', key: 0
    }]);

    const query = {}



    const getGroupList = () => {
        getObject({ url: apis.apiServer.groupList }).then(({ data }) => {
            if (data instanceof Array) {
                const ago = [{ title: '无分组', key: 0 }]
                data.forEach(d => {
                    ago.push({ title: d.name, key: d.id })
                })
                setApiGroupOptions(ago || []);
            }

        })
    }

    // 编辑API
    const handleEditApi = (record: ApiInfo) => {
        setCurrentApi(record);
        setApiModalVisible(true);
    };

    // 其他处理函数保持不变...
    // 保存Mapper
    const handleDeleteApi = (id: number) => {
        deleteObject({ url: apis.apiServer.delete, data: [id] }).then(() => {
            toast.success('API删除成功');
            getList();
        })
    }

    // 表格列配置
    const columns = [
        {
            title: 'API名称',
            dataIndex: 'name',
            key: 'name',
            render: (text: string | null) => text || <Text type="secondary">未命名</Text>,
        },
        {
            title: '路径',
            dataIndex: 'path',
            key: 'path',
            render: (text: string | null) => text || <Text type="secondary">未设置</Text>,
        },
        {
            title: '类型',
            dataIndex: 'type',
            key: 'type',
            render: (text: string | null) => (
                text ? <Tag color="blue">{text}</Tag> : <Text type="secondary">未设置</Text>
            ),
        },
        {
            title: '分组名称',
            dataIndex: 'gidName',
            key: 'gidName',
            render: (gid: number | null) => gid || <Text type="secondary">未设置</Text>,
        },
        {
            title: '操作',
            key: 'action',
            render: (_: any, record: ApiInfo) => (
                <Space size="middle">
                    <Tooltip title=" 编辑">
                        <Button
                            color="default" variant="link"
                            icon={<EditOutlined />}
                            onClick={() => handleEditApi(record)}
                        />
                    </Tooltip>

                    <Tooltip title="预览">
                        <Button
                            type="link"
                            icon={<EyeOutlined />}
                            onClick={() => {
                                setCurrentApi(record);
                                setLookModalVisible(true)
                            }}
                        />
                    </Tooltip>
                    <Tooltip title="下载">
                        <Button
                            color="gold" variant="link"
                            icon={<DownloadOutlined />}
                            onClick={() => {
                                downloadJson(record)
                            }}
                        />
                    </Tooltip>
                    {/* <Button
                        type="link"
                        icon={<PlusOutlined />}
                        onClick={() => handleAddMapper(record)}
                    >
                        添加Mapper
                    </Button> */}
                    <Popconfirm
                        title="确定要删除此API吗？"
                        onConfirm={() => handleDeleteApi(record.id)}
                        okText="确定"
                        cancelText="取消"
                    >
                        <Tooltip title=" 删除">
                            <Button
                                type="link"
                                icon={<DeleteOutlined />}
                                danger
                            />
                        </Tooltip>
                    </Popconfirm>


                </Space>
            ),
        },
    ];

    const getList = () => {
        setLoading(true);
        getObject({ url: apis.apiServer.list, data: { ...page, ...query } })
            .then(({ data }) => {
                setData(data.list);
                setPage({ ...page, total: data.total })

            })
            .finally(() => {
                setLoading(false);
            });
    };

    const handleTableChange = (pagination: any) => {
        setPage({ ...page, pageNum: pagination.current, pageSize: pagination.pageSize })
        getList();
    };


    const onCheck: TreeProps['onCheck'] = (checkedKeys, info) => {
        if (checkedKeys instanceof Array) {
            query.groupIds = checkedKeys.join(",")
            getList();
        }
    };

    const downloadJson = (record: ApiInfo) => {
        const jsonStr = JSON.stringify({ ...record }, null, 2); // 格式化JSON
        const blob = new Blob([jsonStr], { type: 'application/json' });
        const url = URL.createObjectURL(blob);

        const a = document.createElement('a');
        a.href = url;
        a.download = record.name ? record.name : 'data.json';
        a.click();

        URL.revokeObjectURL(url);
    }
    function uploadMultipleJsonFiles(onJsonsLoaded: any) {
        const input = document.createElement('input');
        input.type = 'file';
        input.accept = '.json,application/json';
        input.multiple = true;
        input.style.display = 'none';

        input.onchange = (e) => {
            const files = Array.from(e.target.files);
            if (!files.length) return;
            const jsonList = [];
            let loaded = 0;

            files.forEach((file, idx) => {
                const reader = new FileReader();
                reader.onload = (event) => {
                    try {
                        const json = JSON.parse(event.target.result);
                        jsonList[idx] = json;
                    } catch {
                        jsonList[idx] = { error: 'JSON 文件格式错误', fileName: file.name };
                    }
                    loaded++;
                    if (loaded === files.length) {
                        onJsonsLoaded && onJsonsLoaded(jsonList);
                    }
                };
                reader.readAsText(file);
            });
        };

        document.body.appendChild(input);
        input.click();
        input.addEventListener('change', () => document.body.removeChild(input), { once: true });
    }

    const batchImport = (json: any) => {
        requestBody({ url: apis.apiServer.batchImport, data: json }).then((res) => {
            if (res.data instanceof Array && res.data.length > 0) {
                // const msg = res.data.join("; ")
                // toast.warning(msg)
                api.warning({
                    message: "上传失败接口",
                    description: showImportError(res.data),
                    placement: 'topRight',
                    duration: null
                });

            } else {
                toast.success("导入成功")
            }
            getList();
            getGroupList()

        })
    }

    const handleDeleteAll = () => {
        deleteObject({ url: apis.apiServer.allDelete }).then((res) => {
            toast.success("删除成功")
            getList()
        })
    }

    const handleAllExport = () => {
        downloadBlob({ url: apis.apiServer.allExport })
    }



    React.useEffect(() => {
        if (!apiModalVisible || !groupModalVisible) {
            getList();
            getGroupList()
        }
    }, [apiModalVisible, groupModalVisible]);

    return (
        <div style={{ padding: 24 }}>
            {contextHolder}
            <div className='flex flex-row gap-2'>
                <div className=' w-[20%]'
                    style={{
                        height: "85vh",
                        overflow: 'auto',
                        border: '1px solid #e6e6e6',
                        borderRadius: 8,
                        boxShadow: '0 2px 8px rgba(0,0,0,0.06)',
                        padding: 16,
                        background: '#fafbfc',
                        // margin: '24px auto',
                        width: 300,
                    }}
                >
                    <Tree
                        checkable
                        onCheck={onCheck}
                        treeData={apiGroupOptions}
                    />
                </div>
                <div className=' w-[80%] '>
                    <div style={{ marginBottom: 16 }}>
                        <Button
                            type="primary"
                            icon={<PlusOutlined />}
                            onClick={() => {
                                setCurrentApi(null);
                                setApiModalVisible(true);
                            }}
                        >
                            添加API
                        </Button>

                        <Button
                            style={{ marginLeft: 8 }}
                            color="lime" variant="solid"
                            onClick={() => {
                                setGroupModalVisible(true);
                            }}
                        >
                            设置分组
                        </Button>

                        <Button
                            style={{ marginLeft: 8 }}
                            color="purple" variant="solid"
                            onClick={() => uploadMultipleJsonFiles((jsons) => {
                                console.log(jsons)
                                batchImport(jsons)
                            })}
                        >
                            导入
                        </Button>
                    </div>
                    <div className='flex justify-between items-end mb-2'>
                        <Input style={{ width: '20%' }} placeholder='搜索' onChange={(e) => {
                            query.name = e.target.value
                            getList();
                        }} allowClear />
                        <div>
                            <Button color="default" variant="link" onClick={handleAllExport}>全部导出</Button>
                            <Popconfirm
                                title="确定要清空API吗？"
                                onConfirm={() => handleDeleteAll()}
                                okText="确定"
                                cancelText="取消"
                            >
                                <Button color="danger" variant="link">全部删除</Button>

                            </Popconfirm>

                        </div>
                    </div>
                    {/* 表格代码保持不变... */}

                    <Table
                        columns={columns}
                        dataSource={data}
                        rowKey="id"
                        bordered
                        loading={loading}
                        scroll={{ y: 800 }}
                        pagination={{
                            current: page.pageNum,
                            pageSize: page.pageSize,
                            total: page.total,
                            // showSizeChanger: true,
                            // pageSizeOptions: ['5', '10', '20', '50'],
                            showQuickJumper: true,
                            showTotal: (total) => `共 ${total} 条`,
                        }}
                        onChange={handleTableChange}

                        style={{
                            background: '#fff',
                            borderRadius: 8,
                            boxShadow: '0 2px 8px rgba(0,0,0,0.06)',
                        }}
                    />
                </div>
            </div>
            {/* 使用封装的Modal组件 */}
            <ApiInfoModal
                visible={apiModalVisible}
                onCancel={() => setApiModalVisible(false)}
                onOk={() => setApiModalVisible(false)}
                initialValues={currentApi || undefined}
                confirmLoading={loading}
            />

            <GroupModel
                visible={groupModalVisible}
                onCancel={() => setGroupModalVisible(false)}
                onOk={() => { setGroupModalVisible(false) }}
            />

            <LookApiModal
                visible={lookModalVisible}
                onCancel={() => setLookModalVisible(false)}
                onOk={() => { setLookModalVisible(false) }}
                initialValues={currentApi || undefined}
            />
        </div>
    );
};

export default ApiInfoTable;
